#ifndef _XML_H_
#define _XML_H_

// On MSVC, disable "conditional expression is constant" warning (level 4). 
// This warning is almost impossible to avoid with certain types of templated code
#ifdef _MSC_VER
    #pragma warning(push)
    #pragma warning(disable:4127)   // Conditional expression is constant
#endif

#include "assert.h"
#include "IReadFile.h"

///////////////////////////////////////////////////////////////////////////
// RAPIDXML_PARSE_ERROR

#define RAPIDXML_PARSE_ERROR(what, where) { /*ParseErrorHandler(what, where);*/ massert(0,what); }

/*namespace irr
{
namespace core
{
    void ParseErrorHandler(const char *what, void *where)
	{
		//TODO
	}
}
}*/

///////////////////////////////////////////////////////////////////////////
// Pool sizes

#ifndef RAPIDXML_STATIC_POOL_SIZE
    #define RAPIDXML_STATIC_POOL_SIZE (64 * 1024)
#endif

#ifndef RAPIDXML_DYNAMIC_POOL_SIZE
    #define RAPIDXML_DYNAMIC_POOL_SIZE (64 * 1024)
#endif

#ifndef RAPIDXML_ALIGNMENT
    #define RAPIDXML_ALIGNMENT sizeof(void*)
#endif

namespace irr
{
namespace core
{
	using namespace io;

    // Forward declarations
    template<class Ch> class CXmlNode;
    template<class Ch> class CXmlAttribute;
    template<class Ch> class CXmlDocument;

	typedef CXmlNode<u8>  CXmlNodeC;
	typedef CXmlNode<u16> CXmlNodeU;
    
    enum NodeType
    {
        NT_DOCUMENT,      //!< A document node. Name and value are empty.
        NT_ELEMENT,       //!< An element node. Name contains element name. Value contains text of first data node.
        NT_DATA,          //!< A data node. Name is empty. Value contains data text.
        NT_CDATA,         //!< A CDATA node. Name is empty. Value contains data text.
        NT_COMMENT,       //!< A comment node. Name is empty. Value contains comment text.
        NT_DECLARATION,   //!< A declaration node. Name and value are empty. Declaration parameters (version, encoding and standalone) are in node attributes.
        NT_DOCTYPE,       //!< A DOCTYPE node. Name is empty. Value contains DOCTYPE text.
        NT_PI             //!< A PI node. Name contains target. Value contains instructions.
    };

    const int PARSE_NO_DATA_NODES			= 0x1;            
    const int PARSE_NO_ELEMENT_VALUES		= 0x2;
    const int PARSE_NO_STRING_TERMINATORS	= 0x4;
    const int PARSE_NO_ENTITY_TERMINATORS	= 0x8;
    const int PARSE_NO_UTF8					= 0x10;
    const int PARSE_DECLARATION_NODE		= 0x20;
    const int PARSE_COMMENT_NODES			= 0x40;
    const int PARSE_DOCTYPE_NODE			= 0x80;
    const int PARSE_PI_NODES				= 0x100;
    const int PARSE_VALIDATE_CLOSING_TAGS	= 0x200;
    const int PARSE_TRIM_WHITESPACE			= 0x400;
    const int PARSE_NORMALIZE_WHITESPACE	= 0x800;

    // Compound flags
    
    const int PARSE_DEFAULT = 0;
    const int PARSE_NON_DESTRUCTIVE = PARSE_NO_STRING_TERMINATORS | PARSE_NO_ENTITY_TERMINATORS;
    const int PARSE_FASTEST = PARSE_NON_DESTRUCTIVE | PARSE_NO_DATA_NODES;
    const int PARSE_FULL = PARSE_DECLARATION_NODE | PARSE_COMMENT_NODES | PARSE_DOCTYPE_NODE | PARSE_PI_NODES | PARSE_VALIDATE_CLOSING_TAGS;

    ///////////////////////////////////////////////////////////////////////
    // Internals

    namespace internal
    {
        template<int Dummy>
        struct LookupTables
        {
            static const unsigned char LookupWhitespace[256];           // Whitespace table
            static const unsigned char LookupNodeName[256];             // Node name table
            static const unsigned char LookupText[256];                 // Text table
            static const unsigned char LookupTextPureNoWs[256];         // Text table
            static const unsigned char LookuptextPureWithWs[256];       // Text table
            static const unsigned char LookupAttributeName[256];        // Attribute name table
            static const unsigned char LookupAttributeData1[256];       // Attribute data table with single quote
            static const unsigned char LookupAttributeData1Pure[256];   // Attribute data table with single quote
            static const unsigned char LookupAttributeData2[256];       // Attribute data table with double quotes
            static const unsigned char LookupAttributeData2Pure[256];   // Attribute data table with double quotes
            static const unsigned char LookupDigits[256];               // Digits
            static const unsigned char LookupUpcase[256];               // To uppercase conversion table for ASCII characters
        };

        // Find length of the string
        template<class Ch>
        inline std::size_t Measure(const Ch *p)
        {
            const Ch *tmp = p;
            while (*tmp) 
                ++tmp;
            return tmp - p;
        }

        // Compare strings for equality
        template<class Ch>
        inline bool Compare(const Ch *p1, std::size_t size1, const Ch *p2, std::size_t size2, bool case_sensitive)
        {
            if (size1 != size2)
                return false;
            if (case_sensitive)
            {
                for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2)
                    if (*p1 != *p2)
                        return false;
            }
            else
            {
                for (const Ch *end = p1 + size1; p1 < end; ++p1, ++p2)
                    if (LookupTables<0>::LookupUpcase[static_cast<unsigned char>(*p1)] != LookupTables<0>::LookupUpcase[static_cast<unsigned char>(*p2)])
                        return false;
            }
            return true;
        }
    }

    ///////////////////////////////////////////////////////////////////////
    // Memory pool
    
    template<class Ch = char>
    class CMemoryPool
    {
        
    public:

        typedef void *(AllocFunc)(std::size_t);       // Type of user-defined function used to allocate memory
        typedef void (FreeFunc)(void *);              // Type of user-defined function used to free memory

        CMemoryPool()
            : m_alloc_func(0)
            , m_free_func(0)
        {
            Init();
        }

        ~CMemoryPool()
        {
            Clear();
        }

        CXmlNode<Ch> *AllocateNode(NodeType type, const Ch *name = 0, const Ch *value = 0, std::size_t name_size = 0, std::size_t value_size = 0)
        {
            void *memory = AllocateAlligned(sizeof(CXmlNode<Ch>));
            CXmlNode<Ch> *node = new(memory) CXmlNode<Ch>(type);
            if (name)
            {
                if (name_size > 0)
                    node->Name(name, name_size);
                else
                    node->Name(name);
            }
            if (value)
            {
                if (value_size > 0)
                    node->Value(value, value_size);
                else
                    node->Value(value);
            }
            return node;
        }

        CXmlAttribute<Ch> *AllocateAttribute(const Ch *name = 0, const Ch *value = 0, std::size_t name_size = 0, std::size_t value_size = 0)
        {
            void *memory = AllocateAlligned(sizeof(CXmlAttribute<Ch>));
            CXmlAttribute<Ch> *attribute = new(memory) CXmlAttribute<Ch>;
            if (name)
            {
                if (name_size > 0)
                    attribute->Name(name, name_size);
                else
                    attribute->Name(name);
            }
            if (value)
            {
                if (value_size > 0)
                    attribute->Value(value, value_size);
                else
                    attribute->Value(value);
            }
            return attribute;
        }

        Ch *AllocateString(const Ch *source = 0, std::size_t size = 0)
        {
            assert(source || size);     // Either source or size (or both) must be specified
            if (size == 0)
                size = internal::Measure(source) + 1;
            Ch *result = static_cast<Ch *>(AllocateAlligned(size * sizeof(Ch)));
            if (source)
                for (std::size_t i = 0; i < size; ++i)
                    result[i] = source[i];
            return result;
        }

        CXmlNode<Ch> *CloneNode(const CXmlNode<Ch> *source, CXmlNode<Ch> *result = 0)
        {
            // Prepare result node
            if (result)
            {
                result->RemoveAllAttributes();
                result->RemoveAllNodes();
                result->Type(source->Type());
            }
            else
                result = AllocateNode(source->Type());

            // Clone name and value
            result->Name(source->Name(), source->NameSize());
            result->Value(source->Value(), source->ValueSize());

            // Clone child nodes and attributes
            for (CXmlNode<Ch> *child = source->FirstNode(); child; child = child->Next())
                result->AppendNode(CloneNode(child));
            for (CXmlAttribute<Ch> *attr = source->FirstAttribute(); attr; attr = attr->NextAttribute())
                result->AppendAttribute(AllocateAttribute(attr->Name(), attr->Value(), attr->NameSize(), attr->ValueSize()));

            return result;
        }

        void Clear()
        {
            while (m_begin != m_static_memory)
            {
                char *previous_begin = reinterpret_cast<header *>(Align(m_begin))->previous_begin;
                if (m_free_func)
                    m_free_func(m_begin);
                else
                    delete[] m_begin;
                m_begin = previous_begin;
            }
            Init();
        }

        void SetAllocator(AllocFunc *af, FreeFunc *ff)
        {
            assert(m_begin == m_static_memory && m_ptr == Align(m_begin));    // Verify that no memory is allocated yet
            m_alloc_func = af;
            m_free_func = ff;
        }

    private:

        struct header
        {
            char *previous_begin;
        };

        void Init()
        {
            m_begin = m_static_memory;
            m_ptr = Align(m_begin);
            m_end = m_static_memory + sizeof(m_static_memory);
        }
        
        char *Align(char *ptr)
        {
            std::size_t alignment = ((RAPIDXML_ALIGNMENT - (std::size_t(ptr) & (RAPIDXML_ALIGNMENT - 1))) & (RAPIDXML_ALIGNMENT - 1));
            return ptr + alignment;
        }
        
        char *AllocateRaw(std::size_t size)
        {
            // Allocate
            void *memory;   
            if (m_alloc_func)   // Allocate memory using either user-specified allocation function or global operator new[]
            {
                memory = m_alloc_func(size);
                assert(memory); // Allocator is not allowed to return 0, on failure it must either throw, stop the program or use longjmp
            }
            else
            {
                memory = new char[size];
                if (!memory) 
                    RAPIDXML_PARSE_ERROR("out of memory", 0);
            }
            return static_cast<char *>(memory);
        }
        
        void *AllocateAlligned(std::size_t size)
        {
            // Calculate aligned pointer
            char *result = Align(m_ptr);

            // If not enough memory left in current pool, allocate a new pool
            if (result + size > m_end)
            {
                // Calculate required pool size (may be bigger than RAPIDXML_DYNAMIC_POOL_SIZE)
                std::size_t pool_size = RAPIDXML_DYNAMIC_POOL_SIZE;
                if (pool_size < size)
                    pool_size = size;
                
                // Allocate
                std::size_t alloc_size = sizeof(header) + (2 * RAPIDXML_ALIGNMENT - 2) + pool_size;     // 2 alignments required in worst case: one for header, one for actual allocation
                char *raw_memory = AllocateRaw(alloc_size);
                    
                // Setup new pool in allocated memory
                char *pool = Align(raw_memory);
                header *new_header = reinterpret_cast<header *>(pool);
                new_header->previous_begin = m_begin;
                m_begin = raw_memory;
                m_ptr = pool + sizeof(header);
                m_end = raw_memory + alloc_size;

                // Calculate aligned pointer again using new pool
                result = Align(m_ptr);
            }

            // Update pool and return aligned pointer
            m_ptr = result + size;
            return result;
        }

        char *m_begin;                                      // Start of raw memory making up current pool
        char *m_ptr;                                        // First free byte in current pool
        char *m_end;                                        // One past last available byte in current pool
        char m_static_memory[RAPIDXML_STATIC_POOL_SIZE];    // Static raw memory
        AllocFunc *m_alloc_func;                           // Allocator function, or 0 if default is to be used
        FreeFunc *m_free_func;                             // Free function, or 0 if default is to be used
    };

    ///////////////////////////////////////////////////////////////////////////
    // XML base

    template<class Ch = char>
    class CXmlBase
    {

    public:
        
        ///////////////////////////////////////////////////////////////////////////
        // Construction & destruction
    
        // Construct a base with empty name, value and parent
        CXmlBase(): m_name(0), m_value(0), m_parent(0)
        {
        }

        ///////////////////////////////////////////////////////////////////////////
        // Node data access

        Ch *Name() const
        {
            return m_name ? m_name : Nullstr();
        }

        std::size_t NameSize() const
        {
            return m_name ? m_name_size : 0;
        }

        Ch *Value() const
        {
            return m_value ? m_value : Nullstr();
        }

        std::size_t ValueSize() const
        {
            return m_value ? m_value_size : 0;
        }

        ///////////////////////////////////////////////////////////////////////////
        // Node modification
    
        void Name(const Ch *name, std::size_t size)
        {
            m_name = const_cast<Ch *>(name);
            m_name_size = size;
        }

        void Name(const Ch *name)
        {
            this->Name(name, internal::Measure(name));
        }

        void Value(const Ch *value, std::size_t size)
        {
            m_value = const_cast<Ch *>(value);
            m_value_size = size;
        }

        void Value(const Ch *value)
        {
            this->Value(value, internal::Measure(value));
        }

        ///////////////////////////////////////////////////////////////////////////
        // Related nodes access

        CXmlNode<Ch> *Parent() const
        {
            return m_parent;
        }

    protected:

        static Ch *Nullstr()
        {
            static Ch zero = Ch('\0');
            return &zero;
        }

        Ch *m_name;                         // Name of node, or 0 if no name
        Ch *m_value;                        // Value of node, or 0 if no value
        std::size_t m_name_size;            // Length of node name, or undefined of no name
        std::size_t m_value_size;           // Length of node value, or undefined if no value
        CXmlNode<Ch> *m_parent;             // Pointer to parent node, or 0 if none

    };

    template<class Ch = char>
    class CXmlAttribute: public CXmlBase<Ch>
    {

        friend class CXmlNode<Ch>;
    
    public:

        ///////////////////////////////////////////////////////////////////////////
        // Construction & destruction

        CXmlAttribute()
        {
        }

        ///////////////////////////////////////////////////////////////////////////
        // Related nodes access

        CXmlDocument<Ch> *Document() const
        {
            if (CXmlNode<Ch> *node = this->Parent())
            {
                while (node->Parent())
                    node = node->Parent();
                return node->Type() == NT_DOCUMENT ? static_cast<CXmlDocument<Ch> *>(node) : 0;
            }
            else
                return 0;
        }

        CXmlAttribute<Ch> *PreviousAttribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
        {
            if (name)
            {
                if (name_size == 0)
                    name_size = internal::Measure(name);
                for (CXmlAttribute<Ch> *attribute = m_prev_attribute; attribute; attribute = attribute->m_prev_attribute)
                    if (internal::Compare(attribute->Name(), attribute->NameSize(), name, name_size, case_sensitive))
                        return attribute;
                return 0;
            }
            else
                return this->m_parent ? m_prev_attribute : 0;
        }

        CXmlAttribute<Ch> *NextAttribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
        {
            if (name)
            {
                if (name_size == 0)
                    name_size = internal::Measure(name);
                for (CXmlAttribute<Ch> *attribute = m_next_attribute; attribute; attribute = attribute->m_next_attribute)
                    if (internal::Compare(attribute->Name(), attribute->NameSize(), name, name_size, case_sensitive))
                        return attribute;
                return 0;
            }
            else
                return this->m_parent ? m_next_attribute : 0;
        }

    private:

        CXmlAttribute<Ch> *m_prev_attribute;        // Pointer to previous sibling of attribute, or 0 if none; only valid if parent is non-zero
        CXmlAttribute<Ch> *m_next_attribute;        // Pointer to next sibling of attribute, or 0 if none; only valid if parent is non-zero
    
    };

    ///////////////////////////////////////////////////////////////////////////
    // XML node

    template<class Ch = char>
    class CXmlNode: public CXmlBase<Ch>
    {

    public:

        ///////////////////////////////////////////////////////////////////////////
        // Construction & destruction

        CXmlNode(NodeType type): m_type(type), m_first_node(0), m_first_attribute(0)
        {
        }

        ///////////////////////////////////////////////////////////////////////////
        // Node data access

        NodeType Type() const
        {
            return m_type;
        }

        ///////////////////////////////////////////////////////////////////////////
        // Related nodes access

        CXmlDocument<Ch> *Document() const
        {
            CXmlNode<Ch> *node = const_cast<CXmlNode<Ch> *>(this);
            while (node->Parent())
                node = node->Parent();
            return node->Type() == NT_DOCUMENT ? static_cast<CXmlDocument<Ch> *>(node) : 0;
        }

        CXmlNode<Ch> *FirstNode(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
        {
            if (name)
            {
                if (name_size == 0)
                    name_size = internal::Measure(name);
                for (CXmlNode<Ch> *child = m_first_node; child; child = child->Next())
                    if (internal::Compare(child->Name(), child->NameSize(), name, name_size, case_sensitive))
                        return child;
                return 0;
            }
            else
                return m_first_node;
        }

        CXmlNode<Ch> *LastNode(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
        {
            assert(m_first_node);  // Cannot query for last child if node has no children
            if (name)
            {
                if (name_size == 0)
                    name_size = internal::Measure(name);
                for (CXmlNode<Ch> *child = m_last_node; child; child = child->Previous())
                    if (internal::Compare(child->Name(), child->NameSize(), name, name_size, case_sensitive))
                        return child;
                return 0;
            }
            else
                return m_last_node;
        }

        CXmlNode<Ch> *Previous(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
        {
            assert(this->m_parent);     // Cannot query for siblings if node has no parent
            if (name)
            {
                if (name_size == 0)
                    name_size = internal::Measure(name);
                for (CXmlNode<Ch> *sibling = m_prev_sibling; sibling; sibling = sibling->m_prev_sibling)
                    if (internal::Compare(sibling->Name(), sibling->NameSize(), name, name_size, case_sensitive))
                        return sibling;
                return 0;
            }
            else
                return m_prev_sibling;
        }

        CXmlNode<Ch> *Next(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
        {
            assert(this->m_parent);     // Cannot query for siblings if node has no parent
            if (name)
            {
                if (name_size == 0)
                    name_size = internal::Measure(name);
                for (CXmlNode<Ch> *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling)
                    if (internal::Compare(sibling->Name(), sibling->NameSize(), name, name_size, case_sensitive))
                        return sibling;
                return 0;
            }
            else
                return m_next_sibling;
        }

        CXmlAttribute<Ch> *FirstAttribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
        {
            if (name)
            {
                if (name_size == 0)
                    name_size = internal::Measure(name);
                for (CXmlAttribute<Ch> *attribute = m_first_attribute; attribute; attribute = attribute->m_next_attribute)
                    if (internal::Compare(attribute->Name(), attribute->NameSize(), name, name_size, case_sensitive))
                        return attribute;
                return 0;
            }
            else
                return m_first_attribute;
        }

        CXmlAttribute<Ch> *LastAttribute(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
        {
            if (name)
            {
                if (name_size == 0)
                    name_size = internal::Measure(name);
                for (CXmlAttribute<Ch> *attribute = m_last_attribute; attribute; attribute = attribute->m_prev_attribute)
                    if (internal::Compare(attribute->Name(), attribute->NameSize(), name, name_size, case_sensitive))
                        return attribute;
                return 0;
            }
            else
                return m_first_attribute ? m_last_attribute : 0;
        }

        ///////////////////////////////////////////////////////////////////////////
        // Node modification
    
        void Type(NodeType type)
        {
            m_type = type;
        }

        ///////////////////////////////////////////////////////////////////////////
        // Node manipulation

        void PrependNode(CXmlNode<Ch> *child)
        {
            assert(child && !child->Parent() && child->Type() != NT_DOCUMENT);
            if (FirstNode())
            {
                child->m_next_sibling = m_first_node;
                m_first_node->m_prev_sibling = child;
            }
            else
            {
                child->m_next_sibling = 0;
                m_last_node = child;
            }
            m_first_node = child;
            child->m_parent = this;
            child->m_prev_sibling = 0;
        }

        void AppendNode(CXmlNode<Ch> *child)
        {
            assert(child && !child->Parent() && child->Type() != NT_DOCUMENT);
            if (FirstNode())
            {
                child->m_prev_sibling = m_last_node;
                m_last_node->m_next_sibling = child;
            }
            else
            {
                child->m_prev_sibling = 0;
                m_first_node = child;
            }
            m_last_node = child;
            child->m_parent = this;
            child->m_next_sibling = 0;
        }

        void InsertNode(CXmlNode<Ch> *where, CXmlNode<Ch> *child)
        {
            assert(!where || where->Parent() == this);
            assert(child && !child->Parent() && child->Type() != NT_DOCUMENT);
            if (where == m_first_node)
                PrependNode(child);
            else if (where == 0)
                AppendNode(child);
            else
            {
                child->m_prev_sibling = where->m_prev_sibling;
                child->m_next_sibling = where;
                where->m_prev_sibling->m_next_sibling = child;
                where->m_prev_sibling = child;
                child->m_parent = this;
            }
        }

        void RemoveFirstNode()
        {
            assert(FirstNode());
            CXmlNode<Ch> *child = m_first_node;
            m_first_node = child->m_next_sibling;
            if (child->m_next_sibling)
                child->m_next_sibling->m_prev_sibling = 0;
            else
                m_last_node = 0;
            child->m_parent = 0;
        }

        void RemoveLastNode()
        {
            assert(FirstNode());
            CXmlNode<Ch> *child = m_last_node;
            if (child->m_prev_sibling)
            {
                m_last_node = child->m_prev_sibling;
                child->m_prev_sibling->m_next_sibling = 0;
            }
            else
                m_first_node = 0;
            child->m_parent = 0;
        }

        void RemoveNode(CXmlNode<Ch> *where)
        {
            assert(where && where->Parent() == this);
            assert(FirstNode());
            if (where == m_first_node)
                RemoveFirstNode();
            else if (where == m_last_node)
                RemoveLastNode();
            else
            {
                where->m_prev_sibling->m_next_sibling = where->m_next_sibling;
                where->m_next_sibling->m_prev_sibling = where->m_prev_sibling;
                where->m_parent = 0;
            }
        }

        void RemoveAllNodes()
        {
            for (CXmlNode<Ch> *node = FirstNode(); node; node = node->m_next_sibling)
                node->m_parent = 0;
            m_first_node = 0;
        }

        void PrependAttribute(CXmlAttribute<Ch> *attribute)
        {
            assert(attribute && !attribute->Parent());
            if (FirstAttribute())
            {
                attribute->m_next_attribute = m_first_attribute;
                m_first_attribute->m_prev_attribute = attribute;
            }
            else
            {
                attribute->m_next_attribute = 0;
                m_last_attribute = attribute;
            }
            m_first_attribute = attribute;
            attribute->m_parent = this;
            attribute->m_prev_attribute = 0;
        }

        void AppendAttribute(CXmlAttribute<Ch> *attribute)
        {
            assert(attribute && !attribute->Parent());
            if (FirstAttribute())
            {
                attribute->m_prev_attribute = m_last_attribute;
                m_last_attribute->m_next_attribute = attribute;
            }
            else
            {
                attribute->m_prev_attribute = 0;
                m_first_attribute = attribute;
            }
            m_last_attribute = attribute;
            attribute->m_parent = this;
            attribute->m_next_attribute = 0;
        }

        void InsertAttribute(CXmlAttribute<Ch> *where, CXmlAttribute<Ch> *attribute)
        {
            assert(!where || where->Parent() == this);
            assert(attribute && !attribute->Parent());
            if (where == m_first_attribute)
                PrependAttribute(attribute);
            else if (where == 0)
                AppendAttribute(attribute);
            else
            {
                attribute->m_prev_attribute = where->m_prev_attribute;
                attribute->m_next_attribute = where;
                where->m_prev_attribute->m_next_attribute = attribute;
                where->m_prev_attribute = attribute;
                attribute->m_parent = this;
            }
        }

        void RemoveFirstAttribute()
        {
            assert(FirstAttribute());
            CXmlAttribute<Ch> *attribute = m_first_attribute;
            if (attribute->m_next_attribute)
            {
                attribute->m_next_attribute->m_prev_attribute = 0;
            }
            else
                m_last_attribute = 0;
            attribute->m_parent = 0;
            m_first_attribute = attribute->m_next_attribute;
        }

        void RemoveLastAttribute()
        {
            assert(FirstAttribute());
            CXmlAttribute<Ch> *attribute = m_last_attribute;
            if (attribute->m_prev_attribute)
            {
                attribute->m_prev_attribute->m_next_attribute = 0;
                m_last_attribute = attribute->m_prev_attribute;
            }
            else
                m_first_attribute = 0;
            attribute->m_parent = 0;
        }

        void RemoveAttribute(CXmlAttribute<Ch> *where)
        {
            assert(FirstAttribute() && where->Parent() == this);
            if (where == m_first_attribute)
                RemoveFirstAttribute();
            else if (where == m_last_attribute)
                RemoveLastAttribute();
            else
            {
                where->m_prev_attribute->m_next_attribute = where->m_next_attribute;
                where->m_next_attribute->m_prev_attribute = where->m_prev_attribute;
                where->m_parent = 0;
            }
        }

        void RemoveAllAttributes()
        {
            for (CXmlAttribute<Ch> *attribute = FirstAttribute(); attribute; attribute = attribute->m_next_attribute)
                attribute->m_parent = 0;
            m_first_attribute = 0;
        }
        
    private:

        ///////////////////////////////////////////////////////////////////////////
        // Restrictions

        // No copying
        CXmlNode(const CXmlNode &);
        void operator =(const CXmlNode &);
    
        ///////////////////////////////////////////////////////////////////////////
        // Data members
    
        // Note that some of the pointers below have UNDEFINED values if certain other pointers are 0.
        // This is required for maximum performance, as it allows the parser to omit initialization of 
        // unneded/redundant values.
        //
        // The rules are as follows:
        // 1. first_node and first_attribute contain valid pointers, or 0 if node has no children/attributes respectively
        // 2. last_node and last_attribute are valid only if node has at least one child/attribute respectively, otherwise they contain garbage
        // 3. prev_sibling and next_sibling are valid only if node has a parent, otherwise they contain garbage

        NodeType m_type;                       // Type of node; always valid
        CXmlNode<Ch> *m_first_node;             // Pointer to first child node, or 0 if none; always valid
        CXmlNode<Ch> *m_last_node;              // Pointer to last child node, or 0 if none; this value is only valid if m_first_node is non-zero
        CXmlAttribute<Ch> *m_first_attribute;   // Pointer to first attribute of node, or 0 if none; always valid
        CXmlAttribute<Ch> *m_last_attribute;    // Pointer to last attribute of node, or 0 if none; this value is only valid if m_first_attribute is non-zero
        CXmlNode<Ch> *m_prev_sibling;           // Pointer to previous sibling of node, or 0 if none; this value is only valid if m_parent is non-zero
        CXmlNode<Ch> *m_next_sibling;           // Pointer to next sibling of node, or 0 if none; this value is only valid if m_parent is non-zero

    };

    ///////////////////////////////////////////////////////////////////////////
    // XML document

    template<class Ch = char>
    class CXmlDocument: public CXmlNode<Ch>, public CMemoryPool<Ch>
    {
    
    public:

        //! Constructs empty XML document
        CXmlDocument(): CXmlNode<Ch>(NT_DOCUMENT)
        {
        }

		~CXmlDocument()
		{
			Clear();
		}

        template<int Flags>
        void Parse(Ch *text)
        {
            assert(text);
            
            // Remove current contents
            this->RemoveAllNodes();
            this->RemoveAllAttributes();
            
            // Parse BOM, if any
            ParseBom<Flags>(text);
            
            // Parse children
            while (1)
            {
                // Skip whitespace before node
                Skip<WhitespacePred, Flags>(text);
                if (*text == 0)
                    break;

                // Parse and append new child
                if (*text == Ch('<'))
                {
                    ++text;     // Skip '<'
                    if (CXmlNode<Ch> *node = ParseNode<Flags>(text))
                        this->AppendNode(node);
                }
                else
                    RAPIDXML_PARSE_ERROR("expected <", text);
            }

        }

		template<int Flags>
        void Parse(IReadFile *file)
        {
			assert(file);
			u32 sz = file->getSize();
			if(m_buffer)
			{
				delete[] m_buffer;
				m_buffer = 0;
			}
			m_buffer = new Ch[sz/sizeof(Ch)];
			assert(m_buffer);

			file->read((void*)m_buffer,sz);

			Parse(m_buffer);
		}

        void Clear()
        {
            this->RemoveAllNodes();
            this->RemoveAllAttributes();
            CMemoryPool<Ch>::Clear();
			if(m_buffer)
			{
				delete[] m_buffer;
				m_buffer = 0;
			}
        }
        
    private:

        ///////////////////////////////////////////////////////////////////////
        // Internal character utility functions
        
        // Detect whitespace character
        struct WhitespacePred
        {
            static unsigned char Test(Ch ch)
            {
                return internal::LookupTables<0>::LookupWhitespace[static_cast<unsigned char>(ch)];
            }
        };

        // Detect node name character
        struct NodeNamePred
        {
            static unsigned char Test(Ch ch)
            {
                return internal::LookupTables<0>::LookupNodeName[static_cast<unsigned char>(ch)];
            }
        };

        // Detect attribute name character
        struct AttributeNamePred
        {
            static unsigned char Test(Ch ch)
            {
                return internal::LookupTables<0>::LookupAttributeName[static_cast<unsigned char>(ch)];
            }
        };

        // Detect text character (PCDATA)
        struct TextPred
        {
            static unsigned char test(Ch ch)
            {
                return internal::LookupTables<0>::LookupText[static_cast<unsigned char>(ch)];
            }
        };

        // Detect text character (PCDATA) that does not require processing
        struct TextPureNoWsPred
        {
            static unsigned char Test(Ch ch)
            {
                return internal::LookupTables<0>::LookupTextPureNoWs[static_cast<unsigned char>(ch)];
            }
        };

        // Detect text character (PCDATA) that does not require processing
        struct TextPureWithWsPred
        {
            static unsigned char Test(Ch ch)
            {
                return internal::LookupTables<0>::LookuptextPureWithWs[static_cast<unsigned char>(ch)];
            }
        };

        // Detect attribute value character
        template<Ch Quote>
        struct AttributeValuePred
        {
            static unsigned char Test(Ch ch)
            {
                if (Quote == Ch('\''))
                    return internal::LookupTables<0>::LookupAttributeData1[static_cast<unsigned char>(ch)];
                if (Quote == Ch('\"'))
                    return internal::LookupTables<0>::LookupAttributeData2[static_cast<unsigned char>(ch)];
                return 0;       // Should never be executed, to avoid warnings on Comeau
            }
        };

        // Detect attribute value character
        template<Ch Quote>
        struct AttributeValuePurePred
        {
            static unsigned char Test(Ch ch)
            {
                if (Quote == Ch('\''))
                    return internal::LookupTables<0>::LookupAttributeData1Pure[static_cast<unsigned char>(ch)];
                if (Quote == Ch('\"'))
                    return internal::LookupTables<0>::LookupAttributeData2Pure[static_cast<unsigned char>(ch)];
                return 0;       // Should never be executed, to avoid warnings on Comeau
            }
        };

        // Insert coded character, using UTF8 or 8-bit ASCII
        template<int Flags>
        static void InsertCodedCharacter(Ch *&text, unsigned long code)
        {
            if (Flags & PARSE_NO_UTF8)
            {
                // Insert 8-bit ASCII character
                // Todo: possibly verify that code is less than 256 and use replacement char otherwise?
                text[0] = static_cast<unsigned char>(code);
                text += 1;
            }
            else
            {
                // Insert UTF8 sequence
                if (code < 0x80)    // 1 byte sequence
                {
	                text[0] = static_cast<unsigned char>(code);
                    text += 1;
                }
                else if (code < 0x800)  // 2 byte sequence
                {
	                text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
	                text[0] = static_cast<unsigned char>(code | 0xC0);
                    text += 2;
                }
	            else if (code < 0x10000)    // 3 byte sequence
                {
	                text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
	                text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
	                text[0] = static_cast<unsigned char>(code | 0xE0);
                    text += 3;
                }
	            else if (code < 0x110000)   // 4 byte sequence
                {
	                text[3] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
	                text[2] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
	                text[1] = static_cast<unsigned char>((code | 0x80) & 0xBF); code >>= 6;
	                text[0] = static_cast<unsigned char>(code | 0xF0);
                    text += 4;
                }
                else    // Invalid, only codes up to 0x10FFFF are allowed in Unicode
                {
                    RAPIDXML_PARSE_ERROR("invalid numeric character entity", text);
                }
            }
        }

        // Skip characters until predicate evaluates to true
        template<class StopPred, int Flags>
        static void Skip(Ch *&text)
        {
            Ch *tmp = text;
            while (StopPred::test(*tmp))
                ++tmp;
            text = tmp;
        }

        // Skip characters until predicate evaluates to true while doing the following:
        // - replacing XML character entity references with proper characters (&apos; &amp; &quot; &lt; &gt; &#...;)
        // - condensing whitespace sequences to single space character
        template<class StopPred, class StopPredPure, int Flags>
        static Ch *SkipAndExpandCharacterRefs(Ch *&text)
        {
            // If entity translation, whitespace condense and whitespace trimming is disabled, use plain skip
            if (Flags & PARSE_NO_ENTITY_TERMINATORS && 
                !(Flags & PARSE_NORMALIZE_WHITESPACE) &&
                !(Flags & PARSE_TRIM_WHITESPACE))
            {
                Skip<StopPred, Flags>(text);
                return text;
            }
            
            // Use simple skip until first modification is detected
            Skip<StopPredPure, Flags>(text);

            // Use translation skip
            Ch *src = text;
            Ch *dest = src;
            while (StopPred::test(*src))
            {
                // If entity translation is enabled    
                if (!(Flags & PARSE_NO_ENTITY_TERMINATORS))
                {
                    // Test if replacement is needed
                    if (src[0] == Ch('&'))
                    {
                        switch (src[1])
                        {

                        // &amp; &apos;
                        case Ch('a'): 
                            if (src[2] == Ch('m') && src[3] == Ch('p') && src[4] == Ch(';'))
                            {
                                *dest = Ch('&');
                                ++dest;
                                src += 5;
                                continue;
                            }
                            if (src[2] == Ch('p') && src[3] == Ch('o') && src[4] == Ch('s') && src[5] == Ch(';'))
                            {
                                *dest = Ch('\'');
                                ++dest;
                                src += 6;
                                continue;
                            }
                            break;

                        // &quot;
                        case Ch('q'): 
                            if (src[2] == Ch('u') && src[3] == Ch('o') && src[4] == Ch('t') && src[5] == Ch(';'))
                            {
                                *dest = Ch('"');
                                ++dest;
                                src += 6;
                                continue;
                            }
                            break;

                        // &gt;
                        case Ch('g'): 
                            if (src[2] == Ch('t') && src[3] == Ch(';'))
                            {
                                *dest = Ch('>');
                                ++dest;
                                src += 4;
                                continue;
                            }
                            break;

                        // &lt;
                        case Ch('l'): 
                            if (src[2] == Ch('t') && src[3] == Ch(';'))
                            {
                                *dest = Ch('<');
                                ++dest;
                                src += 4;
                                continue;
                            }
                            break;

                        // &#...; - assumes ASCII
                        case Ch('#'): 
                            if (src[2] == Ch('x'))
                            {
                                unsigned long code = 0;
                                src += 3;   // Skip &#x
                                while (1)
                                {
                                    unsigned char digit = internal::LookupTables<0>::LookupDigits[static_cast<unsigned char>(*src)];
                                    if (digit == 0xFF)
                                        break;
                                    code = code * 16 + digit;
                                    ++src;
                                }
                                InsertCodedCharacter<Flags>(dest, code);    // Put character in output
                            }
                            else
                            {
                                unsigned long code = 0;
                                src += 2;   // Skip &#
                                while (1)
                                {
                                    unsigned char digit = internal::LookupTables<0>::LookupDigits[static_cast<unsigned char>(*src)];
                                    if (digit == 0xFF)
                                        break;
                                    code = code * 10 + digit;
                                    ++src;
                                }
                                InsertCodedCharacter<Flags>(dest, code);    // Put character in output
                            }
                            if (*src == Ch(';'))
                                ++src;
                            else
                                RAPIDXML_PARSE_ERROR("expected ;", src);
                            continue;

                        // Something else
                        default:
                            // Ignore, just copy '&' verbatim
                            break;

                        }
                    }
                }
                
                // If whitespace condensing is enabled
                if (Flags & PARSE_NORMALIZE_WHITESPACE)
                {
                    // Test if condensing is needed                 
                    if (WhitespacePred::Test(*src))
                    {
                        *dest = Ch(' '); ++dest;    // Put single space in dest
                        ++src;                      // Skip first whitespace char
                        // Skip remaining whitespace chars
                        while (WhitespacePred::Test(*src))
                            ++src;
                        continue;
                    }
                }

                // No replacement, only copy character
                *dest++ = *src++;

            }

            // Return new end
            text = src;
            return dest;

        }

        ///////////////////////////////////////////////////////////////////////
        // Internal parsing functions
        
        // Parse BOM, if any
        template<int Flags>
        void ParseBom(Ch *&text)
        {
            // UTF-8?
            if (static_cast<unsigned char>(text[0]) == 0xEF && 
                static_cast<unsigned char>(text[1]) == 0xBB && 
                static_cast<unsigned char>(text[2]) == 0xBF)
            {
                text += 3;      // Skup utf-8 bom
            }
        }

        // Parse XML declaration (<?xml...)
        template<int Flags>
        CXmlNode<Ch> *ParseXmlDeclaration(Ch *&text)
        {
            // If parsing of declaration is disabled
            if (!(Flags & PARSE_DECLARATION_NODE))
            {
                // Skip until end of declaration
                while (text[0] != Ch('?') || text[1] != Ch('>'))
                {
                    if (!text[0])
                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                    ++text;
                }
                text += 2;    // Skip '?>'
                return 0;
            }

            // Create declaration
            CXmlNode<Ch> *declaration = this->allocate_node(NT_DECLARATION);

            // Skip whitespace before attributes or ?>
            Skip<WhitespacePred, Flags>(text);

            // Parse declaration attributes
            ParseNodeAttributes<Flags>(text, declaration);
            
            // Skip ?>
            if (text[0] != Ch('?') || text[1] != Ch('>'))
                RAPIDXML_PARSE_ERROR("expected ?>", text);
            text += 2;
            
            return declaration;
        }

        // Parse XML comment (<!--...)
        template<int Flags>
        CXmlNode<Ch> *ParseComment(Ch *&text)
        {
            // If parsing of comments is disabled
            if (!(Flags & PARSE_COMMENT_NODES))
            {
                // Skip until end of comment
                while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>'))
                {
                    if (!text[0])
                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                    ++text;
                }
                text += 3;     // Skip '-->'
                return 0;      // Do not produce comment node
            }

            // Remember value start
            Ch *value = text;

            // Skip until end of comment
            while (text[0] != Ch('-') || text[1] != Ch('-') || text[2] != Ch('>'))
            {
                if (!text[0])
                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                ++text;
            }

            // Create comment node
            CXmlNode<Ch> *comment = this->allocate_node(NT_COMMENT);
            comment->Value(value, text - value);
            
            // Place zero terminator after comment value
            if (!(Flags & PARSE_NO_STRING_TERMINATORS))
                *text = Ch('\0');
            
            text += 3;     // Skip '-->'
            return comment;
        }

        // Parse DOCTYPE
        template<int Flags>
        CXmlNode<Ch> *ParseDoctype(Ch *&text)
        {
            // Remember value start
            Ch *value = text;

            // Skip to >
            while (*text != Ch('>'))
            {
                // Determine character type
                switch (*text)
                {
                
                // If '[' encountered, scan for matching ending ']' using naive algorithm with depth
                // This works for all W3C test files except for 2 most wicked
                case Ch('['):
                {
                    ++text;     // Skip '['
                    int depth = 1;
                    while (depth > 0)
                    {
                        switch (*text)
                        {
                            case Ch('['): ++depth; break;
                            case Ch(']'): --depth; break;
                            case 0: RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                        }
                        ++text;
                    }
                    break;
                }
                
                // Error on end of text
                case Ch('\0'):
                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                
                // Other character, skip it
                default:
                    ++text;

                }
            }
            
            // If DOCTYPE nodes enabled
            if (Flags & PARSE_DOCTYPE_NODE)
            {
                // Create a new doctype node
                CXmlNode<Ch> *doctype = this->allocate_node(NT_DOCTYPE);
                doctype->Value(value, text - value);
                
                // Place zero terminator after value
                if (!(Flags & PARSE_NO_STRING_TERMINATORS))
                    *text = Ch('\0');

                text += 1;      // skip '>'
                return doctype;
            }
            else
            {
                text += 1;      // skip '>'
                return 0;
            }

        }

        // Parse PI
        template<int Flags>
        CXmlNode<Ch> *ParsePi(Ch *&text)
        {
            // If creation of PI nodes is enabled
            if (Flags & PARSE_PI_NODES)
            {
                // Create pi node
                CXmlNode<Ch> *pi = this->allocate_node(NT_PI);

                // Extract PI target name
                Ch *name = text;
                Skip<NodeNamePred, Flags>(text);
                if (text == name)
                    RAPIDXML_PARSE_ERROR("expected PI target", text);
                pi->Name(name, text - name);
                
                // Skip whitespace between pi target and pi
                Skip<WhitespacePred, Flags>(text);

                // Remember start of pi
                Ch *value = text;
                
                // Skip to '?>'
                while (text[0] != Ch('?') || text[1] != Ch('>'))
                {
                    if (*text == Ch('\0'))
                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                    ++text;
                }

                // Set pi value (verbatim, no entity expansion or whitespace normalization)
                pi->Value(value, text - value);     
                
                // Place zero terminator after name and value
                if (!(Flags & PARSE_NO_STRING_TERMINATORS))
                {
                    pi->Name()[pi->NameSize()] = Ch('\0');
                    pi->Value()[pi->ValueSize()] = Ch('\0');
                }
                
                text += 2;                          // Skip '?>'
                return pi;
            }
            else
            {
                // Skip to '?>'
                while (text[0] != Ch('?') || text[1] != Ch('>'))
                {
                    if (*text == Ch('\0'))
                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                    ++text;
                }
                text += 2;    // Skip '?>'
                return 0;
            }
        }

        // Parse and append data
        // Return character that ends data.
        // This is necessary because this character might have been overwritten by a terminating 0
        template<int Flags>
        Ch ParseAndAppendData(CXmlNode<Ch> *node, Ch *&text, Ch *contents_start)
        {
            // Backup to contents start if whitespace trimming is disabled
            if (!(Flags & PARSE_TRIM_WHITESPACE))
                text = contents_start;     
            
            // Skip until end of data
            Ch *value = text, *end;
            if (Flags & PARSE_NORMALIZE_WHITESPACE)
                end = SkipAndExpandCharacterRefs<TextPred, TextPureWithWsPred, Flags>(text);   
            else
                end = SkipAndExpandCharacterRefs<TextPred, TextPureNoWsPred, Flags>(text);

            // Trim trailing whitespace if flag is set; leading was already trimmed by whitespace skip after >
            if (Flags & PARSE_TRIM_WHITESPACE)
            {
                if (Flags & PARSE_NORMALIZE_WHITESPACE)
                {
                    // Whitespace is already condensed to single space characters by skipping function, so just trim 1 char off the end
                    if (*(end - 1) == Ch(' '))
                        --end;
                }
                else
                {
                    // Backup until non-whitespace character is found
                    while (WhitespacePred::Test(*(end - 1)))
                        --end;
                }
            }
            
            // If characters are still left between end and value (this test is only necessary if normalization is enabled)
            // Create new data node
            if (!(Flags & PARSE_NO_DATA_NODES))
            {
                CXmlNode<Ch> *data = this->allocate_node(NT_DATA);
                data->Value(value, end - value);
                node->AppendNode(data);
            }

            // Add data to parent node if no data exists yet
            if (!(Flags & PARSE_NO_ELEMENT_VALUES)) 
                if (*node->Value() == Ch('\0'))
                    node->Value(value, end - value);

            // Place zero terminator after value
            if (!(Flags & PARSE_NO_STRING_TERMINATORS))
            {
                Ch ch = *text;
                *end = Ch('\0');
                return ch;      // Return character that ends data; this is required because zero terminator overwritten it
            }

            // Return character that ends data
            return *text;
        }

        // Parse CDATA
        template<int Flags>
        CXmlNode<Ch> *ParseCdata(Ch *&text)
        {
            // If CDATA is disabled
            if (Flags & PARSE_NO_DATA_NODES)
            {
                // Skip until end of cdata
                while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>'))
                {
                    if (!text[0])
                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                    ++text;
                }
                text += 3;      // Skip ]]>
                return 0;       // Do not produce CDATA node
            }

            // Skip until end of cdata
            Ch *value = text;
            while (text[0] != Ch(']') || text[1] != Ch(']') || text[2] != Ch('>'))
            {
                if (!text[0])
                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                ++text;
            }

            // Create new cdata node
            CXmlNode<Ch> *cdata = this->allocate_node(NT_CDATA);
            cdata->Value(value, text - value);

            // Place zero terminator after value
            if (!(Flags & PARSE_NO_STRING_TERMINATORS))
                *text = Ch('\0');

            text += 3;      // Skip ]]>
            return cdata;
        }
        
        // Parse element node
        template<int Flags>
        CXmlNode<Ch> *ParseElement(Ch *&text)
        {
            // Create element node
            CXmlNode<Ch> *element = this->allocate_node(NT_ELEMENT);

            // Extract element name
            Ch *name = text;
            Skip<NodeNamePred, Flags>(text);
            if (text == name)
                RAPIDXML_PARSE_ERROR("expected element name", text);
            element->Name(name, text - name);
            
            // Skip whitespace between element name and attributes or >
            Skip<WhitespacePred, Flags>(text);

            // Parse attributes, if any
            ParseNodeAttributes<Flags>(text, element);

            // Determine ending type
            if (*text == Ch('>'))
            {
                ++text;
                ParseNodeContents<Flags>(text, element);
            }
            else if (*text == Ch('/'))
            {
                ++text;
                if (*text != Ch('>'))
                    RAPIDXML_PARSE_ERROR("expected >", text);
                ++text;
            }
            else
                RAPIDXML_PARSE_ERROR("expected >", text);

            // Place zero terminator after name
            if (!(Flags & PARSE_NO_STRING_TERMINATORS))
                element->Name()[element->NameSize()] = Ch('\0');

            // Return parsed element
            return element;
        }

        // Determine node type, and parse it
        template<int Flags>
        CXmlNode<Ch> *ParseNode(Ch *&text)
        {
            // Parse proper node type
            switch (text[0])
            {

            // <...
            default: 
                // Parse and append element node
                return ParseElement<Flags>(text);

            // <?...
            case Ch('?'): 
                ++text;     // Skip ?
                if ((text[0] == Ch('x') || text[0] == Ch('X')) &&
                    (text[1] == Ch('m') || text[1] == Ch('M')) && 
                    (text[2] == Ch('l') || text[2] == Ch('L')) &&
                    WhitespacePred::Test(text[3]))
                {
                    // '<?xml ' - xml declaration
                    text += 4;      // Skip 'xml '
                    return ParseXmlDeclaration<Flags>(text);
                }
                else
                {
                    // Parse PI
                    return ParsePi<Flags>(text);
                }
            
            // <!...
            case Ch('!'): 

                // Parse proper subset of <! node
                switch (text[1])    
                {
                
                // <!-
                case Ch('-'):
                    if (text[2] == Ch('-'))
                    {
                        // '<!--' - xml comment
                        text += 3;     // Skip '!--'
                        return ParseComment<Flags>(text);
                    }
                    break;

                // <![
                case Ch('['):
                    if (text[2] == Ch('C') && text[3] == Ch('D') && text[4] == Ch('A') && 
                        text[5] == Ch('T') && text[6] == Ch('A') && text[7] == Ch('['))
                    {
                        // '<![CDATA[' - cdata
                        text += 8;     // Skip '![CDATA['
                        return ParseCdata<Flags>(text);
                    }
                    break;

                // <!D
                case Ch('D'):
                    if (text[2] == Ch('O') && text[3] == Ch('C') && text[4] == Ch('T') && 
                        text[5] == Ch('Y') && text[6] == Ch('P') && text[7] == Ch('E') && 
                        WhitespacePred::Test(text[8]))
                    {
                        // '<!DOCTYPE ' - doctype
                        text += 9;      // skip '!DOCTYPE '
                        return ParseDoctype<Flags>(text);
                    }

                }   // switch

                // Attempt to skip other, unrecognized node types starting with <!
                ++text;     // Skip !
                while (*text != Ch('>'))
                {
                    if (*text == 0)
                        RAPIDXML_PARSE_ERROR("unexpected end of data", text);
                    ++text;
                }
                ++text;     // Skip '>'
                return 0;   // No node recognized

            }
        }

        // Parse contents of the node - children, data etc.
        template<int Flags>
        void ParseNodeContents(Ch *&text, CXmlNode<Ch> *node)
        {
            // For all children and text
            while (1)
            {
                // Skip whitespace between > and node contents
                Ch *contents_start = text;      // Store start of node contents before whitespace is skipped
                Skip<WhitespacePred, Flags>(text);
                Ch next_char = *text;

            // After data nodes, instead of continuing the loop, control jumps here.
            // This is because zero termination inside parse_and_append_data() function
            // would wreak havoc with the above code.
            // Also, skipping whitespace after data nodes is unnecessary.
            after_data_node:    
                
                // Determine what comes next: node closing, child node, data node, or 0?
                switch (next_char)
                {
                
                // Node closing or child node
                case Ch('<'):
                    if (text[1] == Ch('/'))
                    {
                        // Node closing
                        text += 2;      // Skip '</'
                        if (Flags & PARSE_VALIDATE_CLOSING_TAGS)
                        {
                            // Skip and validate closing tag name
                            Ch *closing_name = text;
                            Skip<NodeNamePred, Flags>(text);
                            if (!internal::Compare(node->Name(), node->NameSize(), closing_name, text - closing_name, true))
                                RAPIDXML_PARSE_ERROR("invalid closing tag name", text);
                        }
                        else
                        {
                            // No validation, just skip name
                            Skip<NodeNamePred, Flags>(text);
                        }
                        // Skip remaining whitespace after node name
                        Skip<WhitespacePred, Flags>(text);
                        if (*text != Ch('>'))
                            RAPIDXML_PARSE_ERROR("expected >", text);
                        ++text;     // Skip '>'
                        return;     // Node closed, finished parsing contents
                    }
                    else
                    {
                        // Child node
                        ++text;     // Skip '<'
                        if (CXmlNode<Ch> *child = ParseNode<Flags>(text))
                            node->AppendNode(child);
                    }
                    break;

                // End of data - error
                case Ch('\0'):
                    RAPIDXML_PARSE_ERROR("unexpected end of data", text);

                // Data node
                default:
                    next_char = ParseAndAppendData<Flags>(node, text, contents_start);
                    goto after_data_node;   // Bypass regular processing after data nodes

                }
            }
        }
        
        // Parse XML attributes of the node
        template<int Flags>
        void ParseNodeAttributes(Ch *&text, CXmlNode<Ch> *node)
        {
            // For all attributes 
            while (AttributeNamePred::Test(*text))
            {
                // Extract attribute name
                Ch *name = text;
                ++text;     // Skip first character of attribute name
                Skip<AttributeNamePred, Flags>(text);
                if (text == name)
                    RAPIDXML_PARSE_ERROR("expected attribute name", name);

                // Create new attribute
                CXmlAttribute<Ch> *attribute = this->allocate_attribute();
                attribute->Name(name, text - name);
                node->AppendAttribute(attribute);

                // Skip whitespace after attribute name
                Skip<WhitespacePred, Flags>(text);

                // Skip =
                if (*text != Ch('='))
                    RAPIDXML_PARSE_ERROR("expected =", text);
                ++text;

                // Add terminating zero after name
                if (!(Flags & PARSE_NO_STRING_TERMINATORS))
                    attribute->Name()[attribute->NameSize()] = 0;

                // Skip whitespace after =
                Skip<WhitespacePred, Flags>(text);

                // Skip quote and remember if it was ' or "
                Ch quote = *text;
                if (quote != Ch('\'') && quote != Ch('"'))
                    RAPIDXML_PARSE_ERROR("expected ' or \"", text);
                ++text;

                // Extract attribute value and expand char refs in it
                Ch *value = text, *end;
                const int AttFlags = Flags & ~PARSE_NORMALIZE_WHITESPACE;   // No whitespace normalization in attributes
                if (quote == Ch('\''))
                    end = SkipAndExpandCharacterRefs<AttributeValuePred<Ch('\'')>, AttributeValuePurePred<Ch('\'')>, AttFlags>(text);
                else
                    end = SkipAndExpandCharacterRefs<AttributeValuePred<Ch('"')>, AttributeValuePurePred<Ch('"')>, AttFlags>(text);
                
                // Set attribute value
                attribute->Value(value, end - value);
                
                // Make sure that end quote is present
                if (*text != quote)
                    RAPIDXML_PARSE_ERROR("expected ' or \"", text);
                ++text;     // Skip quote

                // Add terminating zero after value
                if (!(Flags & PARSE_NO_STRING_TERMINATORS))
                    attribute->Value()[attribute->ValueSize()] = 0;

                // Skip whitespace after attribute value
                Skip<WhitespacePred, Flags>(text);
            }
        }

    
		Ch* m_buffer;
	};

    //! \cond internal
    namespace internal
    {

        // Whitespace (space \n \r \t)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupWhitespace[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  0,  0,  1,  0,  0,  // 0
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 1
             1,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 2
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 3
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 4
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 5
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 6
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 7
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 8
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // 9
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // A
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // B
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // C
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // D
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  // E
             0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0   // F
        };

        // Node name (anything but space \n \r \t / > ? \0)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupNodeName[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  // 2
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  // 3
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
        };

        // Text (i.e. PCDATA) (anything but < \0)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupText[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
        };

        // Text (i.e. PCDATA) that does not require processing when ws normalization is disabled 
        // (anything but < \0 &)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupTextPureNoWs[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
             1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
        };

        // Text (i.e. PCDATA) that does not require processing when ws normalizationis is enabled
        // (anything but < \0 & space \n \r \t)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookuptextPureWithWs[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
             0,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  // 3
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
        };

        // Attribute name (anything but space \n \r \t / < > = ? ! \0)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupAttributeName[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,  1,  1,  // 0
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
             0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  // 2
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  0,  0,  0,  0,  // 3
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
        };

        // Attribute data with single quote (anything but ' \0)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupAttributeData1[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
             1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
        };

        // Attribute data with single quote that does not require processing (anything but ' \0 &)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupAttributeData1Pure[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
             1,  1,  1,  1,  1,  1,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
        };

        // Attribute data with double quote (anything but " \0)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupAttributeData2[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
             1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
        };

        // Attribute data with double quote that does not require processing (anything but " \0 &)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupAttributeData2Pure[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
             0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 0
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 1
             1,  1,  0,  1,  1,  1,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 2
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 3
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 4
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 5
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 6
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 7
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 8
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // 9
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // A
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // B
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // C
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // D
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  // E
             1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1   // F
        };

        // Digits (dec and hex, 255 denotes end of numeric character reference)
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupDigits[256] = 
        {
          // 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 0
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 1
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 2
             0,  1,  2,  3,  4,  5,  6,  7,  8,  9,255,255,255,255,255,255,  // 3
           255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255,  // 4
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 5
           255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255,  // 6
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 7
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 8
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // 9
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // A
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // B
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // C
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // D
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,  // E
           255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255   // F
        };
    
        // Upper case conversion
        template<int Dummy>
        const unsigned char LookupTables<Dummy>::LookupUpcase[256] = 
        {
          // 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  A   B   C   D   E   F
           0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15,   // 0
           16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,   // 1
           32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,   // 2
           48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,   // 3
           64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   // 4
           80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,   // 5
           96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,   // 6
           80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123,124,125,126,127,  // 7
           128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,  // 8
           144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,  // 9
           160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,  // A
           176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,  // B
           192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,  // C
           208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,  // D
           224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,  // E
           240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255   // F
        };
    }
    //! \endcond

}
}

// Undefine internal macros
#undef RAPIDXML_PARSE_ERROR

// On MSVC, restore warnings state
#ifdef _MSC_VER
    #pragma warning(pop)
#endif

#endif
